package com.atguigu.Controller;

import com.atguigu.Utils.R;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * 图片的上传和下载
 */

@RestController
@RequestMapping("common")
public class CommonController {
    @Value("${File.basePath}")
    private String basePath;

    @PostMapping("upload")
    public R upload(@RequestParam("file") MultipartFile file) {
        //由于图片上传到后端是存放在临时文件中的，请求结束后自动删除
        //为了存储该文件，需要转存到指定位置E:\\reggie\\img\\目录下
        File filePath = new File(basePath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }

        //由于每个商家可能使用同名或一样的图片上传，故使用UUID来重新命名图片来防止同名文件被覆盖
        //记住加后缀，此后缀为图片的后缀,例如.png等等
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString()+suffix;

        try {
            file.transferTo(new File(basePath+fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(fileName);
    }

    @GetMapping("download")
    public R download(String name, HttpServletResponse response) {
        //上传照片后回显
        //输入流，读取存储的图片
        try {
            FileInputStream fis = new FileInputStream(new File(basePath+name));

        //输出流，回显到浏览器中,需要使用请求的输出流
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");

            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = fis.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
                outputStream.flush();
            }
            outputStream.close();
            fis.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return null;
        }




}
